'use strict';

const Service = require('egg').Service;
class Task extends Service {
    
    async list(params){
        const { ctx } = this;

        var condition = {};
        if(params.projectId){
            condition.project_id =  params.projectId;
        }
        if(params.parentId){
            condition.parent_id = params.parentId;
        }
        if(params.createUserId){
            condition.create_user_id = params.createUserId;
        }
        if(params.executeUserId){
            condition.execute_user_id = params.executeUserId;
        }
        if(params.followUserId){
            condition.follow_user_id = params.followUserId;
        }
        if(params.status){
            if(params.status == 'pending'){
                condition.status = [0, 1];
            }
        }

        var list = await ctx.model.Task.findAll({
            where: condition,
            order: [["id", 'desc']]
        });

        let rsList = new Array();

        for(let i in list){
            let row = JSON.parse(JSON.stringify(list[i]));
            row.execute_start = row.execute_start ? ctx.helper.formatTime('YYYY-MM-DD HH:mm:ss', row.execute_start) : '';
            row.execute_end = row.execute_end ? ctx.helper.formatTime('YYYY-MM-DD HH:mm:ss', row.execute_end) : '';
            rsList.push(row);
        }

        return rsList;
    }

    async getListAndChild(params){
        let list = await this.list(params);

        for(let i in list){
            let pid = list[i]['id']
            list[i]['children'] = this.list({parentId: pid});
        }
        return list;
    }

    /**
     * 获取任务信息
     * @param {*} id 
     * @returns 
     */
    async info(id){
        const { ctx } = this;

        console.log(id);
        let info = await ctx.model.Task.findOne({
            where : {
                id : id
            }
        })

        return info;
    }


    async save(data){
        const { ctx } = this;

        let rs = null;
        if(data.id){
            rs = await ctx.model.Task.update(data, {where:{id: data.id}});
        } else {
            rs = await ctx.model.Task.create(data);
        }
        return rs;
    }


     async del(id){
        const { ctx } = this;

        var rs = await ctx.model.Task.destroy({where : {id: id}});

        return rs;
     }


    async getTaskTree(params){
        let list = await this.list(params);
        let tree = await this.getTree(0, list);

        return tree;
    }


    async getTree(pid, data){
        let rs = new Array();
        data.forEach(async item => {
            if(item.parent_id == pid){
                let rsItem = JSON.parse(JSON.stringify(item));
                rsItem.children = await this.getTree(rsItem.id, data);
                rs.push(rsItem);
            }
        });

        return rs;
    }

    

    
}

module.exports = Task;